package com.example.mypopupwindow;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button showPopupWindowBtn = findViewById(R.id.show_popup_window_btn);
        showPopupWindowBtn.setOnClickListener(this::showPopupWindowClick);

    }

    /**
     * 显示PopupWindow按钮点击事件
     * @param view 视图对象
     */
    private void showPopupWindowClick(View view) {

        View popupView = getLayoutInflater().inflate(R.layout.popup_view, null);

        // 创建PopupWindow对象
        // view 设置要显示的View
        // width 设置宽度
        // height 设置高度
        // focusable 是否获取焦点，失去焦点，PopupWindow隐藏
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);

        // 设置背景
        popupWindow.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.dog, null));

        // 设置加载动画
//        popupWindow.setAnimationStyle();

        // 设置触摸使能
        popupWindow.setTouchable(true);

        // 设置PopupWindow外面的触摸使能
        popupWindow.setOutsideTouchable(true);

        // 显示PopupWindow
        // view 相对某个控件的位置，正左下方，无偏移
        popupWindow.showAsDropDown(view);

        // view 相对某个控件的位置，正左下方，无偏移
        // xoff x 轴方向的偏移量
        // yoff y 轴方向的偏移量
//        popupWindow.showAsDropDown(view, view.getWidth(), -view.getHeight());

        // 获取popupView上面的按钮
        Button shanghaiBtn = popupView.findViewById(R.id.shanghai_btn);
        shanghaiBtn.setOnClickListener(this::shanghaiBtnClick);

        Button beijingBtn = popupView.findViewById(R.id.beijing_btn);
        beijingBtn.setOnClickListener(this::beijingBtnClick);
    }

    /**
     * 北京按钮点击事件
     * @param view 按钮
     */
    private void beijingBtnClick(View view) {
        Log.i(TAG, "beijingBtnClick: 你住在北京吗？");
        if (popupWindow != null) {
            // popupWindow 隐藏
            popupWindow.dismiss();
        }
    }

    /**
     * 上海按钮点击事件
     * @param view 按钮
     */
    private void shanghaiBtnClick(View view) {
        Log.i(TAG, "shanghaiBtnClick: 你住在上海吗？");
        if (popupWindow != null) {
            // popupWindow 隐藏
            popupWindow.dismiss();
        }
    }
}